package com.masiyi.github.template;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.masiyi.github.config.GithubProperties;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author masiyi
 */
@Slf4j
public class GithubTemplate {


    private GithubProperties githubProperties;

    public GithubTemplate(GithubProperties githubProperties) {
        this.githubProperties = githubProperties;
    }

    /**
     * 上传文件
     */
    public String putObject(InputStream inputStream, String message, String fileName) {
        //InputStream 转Base64
        String base64 = Base64.encode(inputStream);
        String url = githubProperties.getHost() + "/repos/" + githubProperties.getOwner() + "/"
                + githubProperties.getRepo() + "/contents/" + fileName;

        Map<String, Object> map = new HashMap<>();
        map.put("message", message);

        map.put("content", base64);
        Map<String, String> committer = new HashMap<>();
        committer.put("name", githubProperties.getOwner());
        committer.put("email", githubProperties.getEmail());
        map.put("committer", committer);
        String body = null;
        try (HttpResponse httpResponse = HttpRequest
                .put(url)
                .header("Authorization", "Bearer " + githubProperties.getAuthorization())
                .body(JSON.toJSONString(map))
                .execute()) {
            body = httpResponse.body();
        }
        log.info("body:{}", body);
        return Optional.ofNullable(JSON.parseObject(body))
                .map(json -> json.getJSONObject("content"))
                .map(json -> json.getString("download_url"))
                .orElse(null);

    }


}
